package com.example.furniture.controller;

import com.example.furniture.entity.Category;
import com.example.furniture.service.CategoryService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.List;

/**
 * 分类管理控制器
 * 提供家具分类的增删改查功能
 * 
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/categories")
@CrossOrigin(origins = "*") // 允许跨域访问，用于前端调用
public class CategoryController {

    private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);
    private final CategoryService categoryService;

    /**
     * 构造函数，注入分类服务
     * 
     * @param categoryService 分类服务实例
     */
    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/hello")
    public String hello() {
        logger.info("分类服务健康检查");
        return "Category service is running";
    }

    /**
     * 获取所有分类列表
     * 
     * @return 分类列表
     */
    @GetMapping
    public ResponseEntity<List<Category>> list() {
        try {
            logger.info("获取所有分类列表");
            List<Category> categories = categoryService.listAll();
            logger.info("成功获取分类列表，共{}条记录", categories.size());
            return ResponseEntity.ok(categories);
        } catch (Exception e) {
            logger.error("获取分类列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据ID获取分类信息
     * 
     * @param id 分类ID
     * @return 分类信息，如果不存在返回404
     */
    @GetMapping("/{id}")
    public ResponseEntity<Category> get(@PathVariable("id") Long id) {
        try {
            logger.info("获取分类信息，ID: {}", id);
            Category category = categoryService.getById(id);
            if (category == null) {
                logger.warn("分类不存在，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(category);
        } catch (Exception e) {
            logger.error("获取分类信息失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 创建新分类
     * 
     * @param category 分类信息
     * @return 创建的分类信息
     */
    @PostMapping
    public ResponseEntity<Category> create(@Valid @RequestBody Category category) {
        try {
            logger.info("创建新分类: {}", category.getName());
            Category saved = categoryService.create(category);
            logger.info("分类创建成功，ID: {}, 名称: {}", saved.getId(), saved.getName());
            return ResponseEntity.created(URI.create("/categories/" + saved.getId())).body(saved);
        } catch (Exception e) {
            logger.error("创建分类失败: {}", category.getName(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新分类信息
     * 
     * @param id 分类ID
     * @param category 更新的分类信息
     * @return 更新后的分类信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<Category> update(@PathVariable("id") Long id, @Valid @RequestBody Category category) {
        try {
            logger.info("更新分类信息，ID: {}", id);
            Category existingCategory = categoryService.getById(id);
            if (existingCategory == null) {
                logger.warn("分类不存在，无法更新，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            Category updated = categoryService.update(id, category);
            logger.info("分类更新成功，ID: {}, 名称: {}", id, updated.getName());
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            logger.error("更新分类失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除分类
     * 
     * @param id 分类ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") Long id) {
        try {
            logger.info("删除分类，ID: {}", id);
            Category existingCategory = categoryService.getById(id);
            if (existingCategory == null) {
                logger.warn("分类不存在，无法删除，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            categoryService.delete(id);
            logger.info("分类删除成功，ID: {}", id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            logger.error("删除分类失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}